package com.xiaouyudeguang.common.interceptor;

import com.xiaouyudeguang.common.config.RouteConfig;
import com.xiaouyudeguang.common.constants.Headers;
import com.xiaouyudeguang.common.utils.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

/**
 * <p>
 * Feign拦截器
 * </p>
 *
 * @author zg
 * @since 2020/12/21
 */
@Data
@Slf4j
@Configuration
@ConfigurationProperties("api.feign")
public class FeignInterceptor implements RequestInterceptor {

    private String baseUrl;

    private List<String> ignoreHeaders = Arrays.asList(
            "Content-Length", "content-length",
            "Content-Type", "content-type",
            "Connection", "connection",
            "tenant_id", "app_id");

    @Autowired
    private RouteConfig routeConfig;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header(Headers.TRACE_ID, MDC.get(Headers.TRACE_ID));
        if (RequestContextHolder.getRequestAttributes() == null) {
            requestTemplate.header(Headers.FROM, requestTemplate.headers().get(Headers.APP_ID));
            return;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (StringUtils.isBlank(request.getHeader(Headers.AUTHORIZATION))) {
            requestTemplate.header(Headers.FROM, requestTemplate.headers().get(Headers.APP_ID));
        }
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            if (!ignoreHeaders.contains(name)) {
                requestTemplate.header(name, value);
            }
        }
    }
}


